package com.jyy.prefabricated.service;

import com.jyy.prefabricated.entity.Course;
import com.jyy.prefabricated.entity.CourseFile;
import com.jyy.prefabricated.enums.CourseTypeEnum;
import com.jyy.prefabricated.exception.CustomException;
import com.jyy.prefabricated.mapper.CourseFileMapper;
import com.jyy.prefabricated.mapper.CourseMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * @version 1.0.0
 * @author: zjj
 */

@Service
public class CourseFileService {

    @Value("${bos.bucketName}")
    private String bucketName; //所属区域名

    @Autowired
    private CourseFileMapper courseFileMapper;

    @Autowired
    private CourseMapper courseMapper;

    @Autowired
    private BosService bosService;

    /**
     * 新增
     * @param courseFile
     * @return
     */
    public int insert(CourseFile courseFile){
        courseFileMapper.insert(courseFile);
        return courseFile.getId();
    }

    /**
     * 更新
     * @param courseFile
     * @return
     */
    public int update(CourseFile courseFile){
        if(courseFile.getId() == null){
            throw new CustomException("参数id不能为空");
        }
        return courseFileMapper.updateByPrimaryKeySelective(courseFile);
    }

    /**
     * 删除文件
     * @param id
     * @return
     */
    public int delete(Integer id){
        CourseFile courseFile = courseFileMapper.selectByPrimaryKey(id);
        if(courseFile.getCourseId() != null){
            Course course = courseMapper.selectByPrimaryKey(courseFile.getCourseId());
            if(course.getType().equals(CourseTypeEnum.RECORDING.getValue())){
                //删除视频另外处理

            } else {
                String path = courseFile.getPath();
                String objectKey = path.substring(path.lastIndexOf('/') +1);
                bosService.deleteObject(bucketName,objectKey);
            }
        }
        return courseFileMapper.deleteByPrimaryKey(id);
    }

    /**
     * 查询文件详情
     * @param id
     * @return
     */
    public CourseFile selectById(Integer id){
        return courseFileMapper.selectByPrimaryKey(id);
    }

    /**
     * 查询课程相关文件
     * @param courseId  课程id
     * @return
     */
    public List<CourseFile> selectByCourseId(Integer courseId){
        return courseFileMapper.selectByCourseId(courseId);
    }

}
